package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryList() {
        //先查redis
        String key = RedisConstants.CACHE_SHOP_TYPR_KEY+ UUID.randomUUID().toString(true);
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        List<ShopType> typeList = null;
        if(shopTypeJson != null) {//redis查到直接返回
            typeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(typeList);
        }
        //没查到去查数据库
        typeList = this.list(new LambdaQueryWrapper<ShopType>()
                .orderByAsc(ShopType::getSort));
        if(Objects.isNull(typeList)) {//没查到直接返回报错
            return Result.fail("店铺类型不存在");
        }
        //查到了，写入redis，并返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList),
                RedisConstants.CACHE_SHOP_TYPR_TTL, TimeUnit.HOURS);
        return Result.ok(typeList);
    }
}
